package com.example.foreapp;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

@SuppressWarnings("deprecation")
public class MainActivity extends ActionBarActivity implements
		OnItemClickListener,OnClickListener {

	private DbOpenHelper db;
	private ListView applist;
	private PackageManager pm;
	public static final String SERVICE_ACTION="com.example.foreService";
	Button btn_add,btn_favor,btn_start,btn_stop;
	private Menu menu;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		db = DbUtil.getIns(this);
		pm = this.getPackageManager();
		applist = (ListView) findViewById(R.id.fapplist);
		
		List<ActivityInfo> ainfos=getActivitys();
		applist.setAdapter(new ActivitysAdapter<ActivityInfo>(ainfos));
		applist.setOnItemClickListener(this);
		applist.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				ActivityInfo info=(ActivityInfo)parent.getItemAtPosition(position);
				info.setFavor(true);
				db.updateRecode(info);
				Toast.makeText(getApplicationContext(), "添加"+info.getClassName(), Toast.LENGTH_SHORT).show();
				return true;
			}
			
		});
		btn_add=(Button)findViewById(R.id.btn_add);
		btn_favor=(Button)findViewById(R.id.btn_favor);
		btn_start=(Button)findViewById(R.id.btn_start);
		btn_stop=(Button)findViewById(R.id.btn_stop);
		btn_add.setOnClickListener(this);
		btn_favor.setOnClickListener(this);
		btn_start.setOnClickListener(this);
		btn_stop.setOnClickListener(this);
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		RefleshList();
		super.onResume();
	}
	
	
	
	private List<ActivityInfo> getActivitys(){
		Cursor c=db.query("time", false);
		List<ActivityInfo> list=new ArrayList<ActivityInfo>();
		ActivityInfo info=null;
		while(c.moveToNext()){
			info=new ActivityInfo();
			info.setLabel(c.getString(c.getColumnIndex("applabel")));
			info.setClassName(c.getString(c.getColumnIndex("classname")));
			info.setTime(c.getString(c.getColumnIndex("time")));
			info.setPkgName(c.getString(c.getColumnIndex("packagename")));
			String f=c.getString(c.getColumnIndex("favor"));
			info.setFavor("t".equals(f));
			list.add(info);
		}
		c.close();
		return list;
	}
	
	

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		int id=v.getId();
		switch (id) {
		case R.id.btn_start:
			onOptionsItemSelected(menu.findItem(R.id.action_start));
			break;
		case R.id.btn_stop:
			onOptionsItemSelected(menu.findItem(R.id.action_stop));
			break;
		case R.id.btn_add:
			onOptionsItemSelected(menu.findItem(R.id.action_add));
			break;
		case R.id.btn_favor:
			onOptionsItemSelected(menu.findItem(R.id.favorite));
			break;
		}
		
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ActivityInfo info=(ActivityInfo)parent.getItemAtPosition(position);
		Intent intent=new Intent();
		intent.setClassName(info.getPkgName(), info.getClassName());
		intent.setPackage(info.getPkgName());
		try {
			startActivity(intent);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(getApplicationContext(), info.getClassName()+"不存在", Toast.LENGTH_SHORT).show();
		}
		
	}

	class ActivitysAdapter<T extends ActivityInfo> extends BaseAdapter {

		private List<ActivityInfo> apps;

		public ActivitysAdapter(List<ActivityInfo> mapps) {
			super();
			apps = mapps;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return apps.size();
		}

		@Override
		public ActivityInfo getItem(int position) {
			// TODO Auto-generated method stub
			return apps.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			// TODO Auto-generated method stub
			View view = null;
			Holder holder = null;
			if (convertView == null || convertView.getTag() == null) {
				view = LayoutInflater.from(getApplicationContext()).inflate(
						R.layout.app_list_item, null);
				holder = new Holder();
				holder.appicon = (ImageView) view.findViewById(R.id.appicon);
				holder.label = (TextView) view.findViewById(R.id.appname);
				holder.packagename = (TextView) view
						.findViewById(R.id.pathname);
				holder.favor=(ImageView)view.findViewById(R.id.appfavor);
				view.setTag(holder);
			} else {
				view = convertView;
				holder = (Holder) convertView.getTag();
			}
			ActivityInfo info = getItem(position);
			Intent aIntent = new Intent(Intent.ACTION_MAIN, null);
			aIntent.setPackage(info.getPkgName());
			List<ResolveInfo> resolveInfos = pm.queryIntentActivities(aIntent,
					PackageManager.MATCH_DEFAULT_ONLY);
			Collections.sort(resolveInfos,
					new ResolveInfo.DisplayNameComparator(pm));
			if (resolveInfos.size() > 0) {
				holder.appicon.setImageDrawable(resolveInfos.get(0)
						.loadIcon(pm));
			}
			holder.favor.setVisibility(info.isFavor()?View.VISIBLE:View.GONE);
			holder.label.setText(info.getLabel());
			holder.packagename.setText(info.getPkgName());
			return view;
		}

	}

	static class Holder {
		ImageView appicon;
		TextView label;
		TextView packagename;
		ImageView favor;

	}
	
	private void RefleshList(){
		ActivitysAdapter<ActivityInfo> adapter=new ActivitysAdapter<ActivityInfo>(getActivitys());
		applist.setAdapter(adapter);
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		this.menu=menu;
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.reflesh) {
			RefleshList();
		}
		if(id==R.id.action_start){
			Intent intent=new Intent(SERVICE_ACTION);
			intent.setPackage("com.example.foreapp");
			startService(intent);
		} 
		if(id==R.id.action_stop){
			Intent intent=new Intent(SERVICE_ACTION);
			intent.setPackage("com.example.foreapp");
			intent.putExtra("action", "stop");
			startService(intent);
		}
		if(id==R.id.action_add){
			Intent intent=new Intent(this,AddActivity.class);
			startActivity(intent);
		}
		if(id==R.id.favorite){
			Intent intent=new Intent(this,FavoriteActivity.class);
			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}
}
